package com.example.HelloSpace.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowMetrics;

public class ViewUtils {
    public static void resizeViewByWidth(Context context, View view,float widthRatio,float heightRatio){
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            WindowManager windowManager = activity.getWindowManager();

            int screenWidth = 0;
            int screenHeight = 0;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                WindowMetrics windowMetrics = windowManager.getCurrentWindowMetrics();
                Rect bounds = windowMetrics.getBounds();
                screenWidth = bounds.width();
                screenHeight = bounds.height();
            } else {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                windowManager.getDefaultDisplay().getMetrics(displayMetrics);
                screenWidth = displayMetrics.widthPixels;
                screenHeight = displayMetrics.heightPixels;
            }

            // 根据提供的比例计算新的宽度和高度
            int newWidth = (int) (screenWidth * widthRatio); // 设置新的宽度
            int newHeight = (int) (screenWidth * heightRatio); // 注意这里使用的是 screenHeight 乘以 heightRatio

            // 获取当前的 LayoutParams 并修改它们
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if (params != null) {
                params.width = newWidth;
                params.height = newHeight;
                view.setLayoutParams(params);
            }
        }
    }
}
